package com.sso.filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserFilter implements Filter {

    private final String TICKET_KEY = "Ticket_Granting_Ticket";
    private String server;
    private String app;

    @Override
    public void init (FilterConfig filterConfig) throws ServletException {
        server = filterConfig.getInitParameter("server");
        app = filterConfig.getInitParameter("app");
    }

    @Override
    public void doFilter (ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        String ticket = null;
        // 获取 request 中的 cookies
        Cookie[] requestCookies = ((HttpServletRequest)request).getCookies();

        // 如果 requestCookies 中包含指定名称的 ticket 值，就取出来放入 ticket
        if (requestCookies != null) {
            for (Cookie cookie : requestCookies) {
                if (cookie.getName().equals(TICKET_KEY)) {
                    ticket = cookie.getValue();
                    break;
                }
            }
        }

        // 如果 ticket 不为 null
        if (ticket != null) {
            ((HttpServletResponse)response).addCookie(new Cookie(TICKET_KEY, ticket));
            filterChain.doFilter(request, response);
            return;
        }

        // 如果是从 server login 跳转过来的，queryString 里会携带 ticket
        ticket = request.getParameter("ticket");
        if (ticket != null && ticket.trim() != "") {
            ((HttpServletResponse)response).addCookie(new Cookie(TICKET_KEY, ticket));
            filterChain.doFilter(request, response);
        } else {
            String path = server + "/ssoLogin?source=" + app;
            System.out.println(path);
            ((HttpServletResponse)response).sendRedirect(server + "/ssoLogin?source=" + app);
        }
    }

    @Override
    public void destroy () {}

}
